package io.choerodon.iam.infra.utils.rank;

import org.apache.commons.lang.StringUtils;

import io.choerodon.core.exception.CommonException;

/**
 * Created by jian_zhang02@163.com on 2018/5/28.
 */
public class RankUtil {

    private RankUtil(){}

    public static String mid(){
        AgileRank minRank = AgileRank.min();
        AgileRank maxRank = AgileRank.max();
        return minRank.between(maxRank).format();
    }

    /**
     * 获取比rank大的排序值
     *
     * @param rank
     * @return
     */
    public static String genNext(String rank){
        return AgileRank.parse(rank).genNext().format();
    }

    /**
     * 获取比minRank小的排序值
     *
     * @param minRank
     * @return
     */
    public static String genPre(String minRank) {
        return AgileRank.parse(minRank).genPrev().format();
    }

    public static String between(String leftRank, String rightRank) {
        AgileRank left = AgileRank.parse(leftRank);
        AgileRank right = AgileRank.parse(rightRank);
        return left.between(right).format();
    }

    public static enum Operation {
        INSERT {
            @Override
            public String getRank(String lastRank, String nextRank) {
                String rank;
                if (StringUtils.isEmpty(lastRank) && StringUtils.isEmpty(nextRank)) {
                    rank = RankUtil.mid();
                } else {
                    rank = super.getRank(lastRank, nextRank);
                }

                return rank;
            }
        },
        UPDATE {
            @Override
            public String getRank(String lastRank, String nextRank) {
                String rank;
                if (StringUtils.isEmpty(lastRank) && StringUtils.isEmpty(nextRank)) {
                    rank = null;
                } else {
                    rank = super.getRank(lastRank, nextRank);
                }

                return rank;
            }
        };

        private Operation() {
        }

        public String getRank(String lastRank, String nextRank) {
            if (StringUtils.isEmpty(lastRank) && StringUtils.isEmpty(nextRank)) {
                throw new CommonException("error.get.rank", new Object[0]);
            } else {
                String rank;
                if (StringUtils.isEmpty(lastRank)) {
                    lastRank = RankUtil.genPre(nextRank);
                    rank = RankUtil.between(lastRank, nextRank);
                } else if (StringUtils.isEmpty(nextRank)) {
                    nextRank = RankUtil.genNext(lastRank);
                    rank = RankUtil.between(lastRank, nextRank);
                } else {
                    rank = RankUtil.between(lastRank, nextRank);
                }
                return rank;
            }
        }
    }
}
